import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Statistic,
  Card,
  Row,
  Col,
  Button,
  Input,
  Menu,
  Space,
  Table,
  Dropdown,
  Tabs,
  message,
  Divider,
  Tag,
  Badge,
  Modal,
  Popconfirm,
} from 'antd';
import { connect } from 'umi';
import {
  ArrowUpOutlined,
  HistoryOutlined,
  SyncOutlined,
  DownOutlined,
  RightOutlined,
  StopOutlined,
  MoneyCollectOutlined,
} from '@ant-design/icons';
import moment from 'moment';

const { TabPane } = Tabs;
const { Search } = Input;
const currControl = 'Edu_CashOutAmtHistory';
const statusInfo = (record: any) => {
  switch (record.status) {
    case 1:
      return <Tag color="green">已完成</Tag>;
    case 2:
      return <Tag color="red">申请中</Tag>;
    case 3:
      return <Tag color="geekblue">已驳回</Tag>;
    default:
      return <Tag color="orange">未处理</Tag>;
  }
};
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      datas: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      payload: {},
      record: {},
      disName: '',
      unApprvNum: 0,
      unCompleteNum: 0,
    };
  }
  componentDidMount() {
    this.fetchDatas(-1, true);
  }
  fetchDatas = (status: number = -1, isAll: boolean = false) => {
    this.setState({ loading: true });
    const { pageIndex, pageSize, disName } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: (pageIndex - 1) * pageSize,
          MaxResultCount: pageSize,
          disName,
          status,
        },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource = resp.result.items;
          if (isAll) {
            let unApprvNum = dataSource.filter((o: any) => o.status == 2).length;
            let apprvNum = dataSource.filter((o: any) => o.status == 1).length;
            let denyNum = dataSource.filter((o: any) => o.status == 3).length;
            let totalAmt: number = 0;
            let payAmt: number = 0;
            let waitAmt: number = 0;
            let frozenAmt: number = 0;
            dataSource.forEach((element: any) => {
              totalAmt += element.commissionAmt;
              if(element.status === 1){
                payAmt += element.cashOutAmt;
              }
              if (element.status === 2) {
                waitAmt += element.nowCashOutAmt;
              }
              if (element.status === 3) {
                frozenAmt += element.nowCashOutAmt;
              }
            });

            this.setState({
              unApprvNum,
              apprvNum,
              denyNum,
              totalAmt,
              payAmt,
              waitAmt,
              frozenAmt,
            });
          }
          this.setState({ loading: false, dataSource, totalCount: resp.result?.totalCount });
        }
      });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  callback = (key: any) => {
    let state: number = parseInt(key);
    if (state < 4) {
      this.fetchDatas(state, false);
    } else {
      if (state === 4) {
        this.fetchDatas(-1, false);
      } else if (state === 5) {
        this.fetchDatas(-1, false);
      } else {
        this.fetchDatas(-1, false);
      }
    }
  };
  handleActionOk = () => {
    const { reason, rejuctStatus, selectedRowKeys } = this.state;
    this.props
      .dispatch({
        type: 'Abp/updateStatus',
        payload: { id: selectedRowKeys.join(','), status: rejuctStatus, reason },
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.success) {
          message.info('执行成功！');
          this.fetchDatas();
        }
      });
  };
  handleMenuClick = (e: any) => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length <= 0) {
      message.warning('请至少选择一项！');
      return;
    }

    this.setState({ rejuctStatus: e.key }, () => {
      if (e.key == '1') {
        this.handleActionOk();
      } else {
        this.swithModel2(true);
      }
    });
  };
  handleAct = (id: any, status: any) => {
    const { reason } = this.state;
    this.props
      .dispatch({
        type: 'Abp/updateStatus',
        payload: { id, status, reason },
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.success) {
          message.info('执行成功！');
          this.fetchDatas();
        }
      });
  };
  onSearch = (value: any) => {
    var disName = this.state.disName;
    disName = value;
    this.setState({ disName }, () => {
      this.fetchDatas();
    });
  };
  swithModel = (visible: boolean, record = null) => {
    this.setState({ visible, record });
  };
  swithModel2 = (visible2: boolean, record = null) => {
    this.setState({ visible2, record });
  };
  render() {
    const {
      loading,
      dataSource,
      selectedRowKeys,
      totalCount,
      pageSize,
      unApprvNum,
      apprvNum,
      denyNum,
      totalAmt,
      payAmt,
      waitAmt,
      frozenAmt,
      record,
    } = this.state;
    const columns: any = [
      {
        title: '序号',
        width: 80,
        align: 'center',
        key: 'index',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '申请金额（元）',
        dataIndex: 'nowCashOutAmt',
        width: 150,
        render: (text: string) => <span>￥ {text}</span>,
      },
      {
        title: '申请人',
        dataIndex: 'applyUser',
        render: (text: string, record: any) => <span>{record.tDistributor.disbName}</span>,
      },
      {
        title: '收款账号',
        dataIndex: 'accountNum',
        render: (text: string, record: any) => <span>{record.tDistributor.bankAccount}</span>,
      },
      {
        title: '申请时间',
        dataIndex: 'creationTime',
        render: (text: string) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
      },
      {
        title: '当前状态',
        render: (record: any) => <span>{statusInfo(record)}</span>,
      },
      {
        title: '驳回原因',
        dataIndex: 'reason',
        width: 200,
        ellipsis: true,
      },
      {
        title: '处理时间',
        dataIndex: 'handleTime',
        render: (text: string) => (
          <span>{text ? moment(text).format('YYYY-MM-DD hh:mm:ss') : ''}</span>
        ),
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm title="确定通过?" onConfirm={() => this.handleAct(record.id, 1)}>
                <Button disabled={record.status == 3} type="primary">通过</Button>
              </Popconfirm>
              <Divider type="vertical" />
              <Popconfirm title="确定驳回?" onConfirm={() => this.swithModel(true, record)} >
                <Button disabled={record.status == 1} danger>驳回</Button>
              </Popconfirm>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="1" icon={<RightOutlined />}>
          批量通过
        </Menu.Item>
        <Menu.Item key="3" icon={<RightOutlined />}>
          批量驳回
        </Menu.Item>
      </Menu>
    );
    return (
      <PageHeaderWrapper title={false}>
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <Card>
              <Statistic
                title="佣金总额"
                value={totalAmt}
                precision={2}
                valueStyle={{ color: '#FF5252' }}
                prefix={<MoneyCollectOutlined />}
                suffix="元"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已提现金额"
                value={payAmt}
                precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<ArrowUpOutlined />}
                suffix="￥"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="待打款金额"
                value={waitAmt}
                precision={2}
                valueStyle={{ color: '#FBC02D' }}
                prefix={<HistoryOutlined />}
                suffix="￥"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已驳回金额"
                value={frozenAmt}
                precision={2}
                valueStyle={{ color: '#607D8B' }}
                prefix={<StopOutlined />}
                suffix="￥"
              />
            </Card>
          </Col>
        </Row>
        <Card>
          <Space style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              onClick={() => this.fetchDatas()}
              loading={loading}
              icon={<SyncOutlined />}
            >
              刷新
            </Button>
            <Dropdown overlay={menu}>
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
            <Search
              style={{ width: 240 }}
              placeholder="输入关键词搜索"
              onSearch={(value) => this.onSearch(value)}
            />
          </Space>
          <Tabs defaultActiveKey="-1" type="card" onChange={this.callback}>
            <TabPane tab={'全部（' + totalCount + '）'} key="-1"></TabPane>
            <TabPane tab={<Badge count={unApprvNum}>未处理</Badge>} key="2"></TabPane>
            <TabPane tab={'已通过（' + apprvNum + '）'} key="1"></TabPane>
            <TabPane tab={'已驳回（' + denyNum + '）'} key="3"></TabPane>
          </Tabs>
          <Table
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataSource}
            pagination={{
              onChange: (page) => {
                this.setState({ pageIndex: page }, () => {
                  this.fetchDatas();
                });
              },
              pageSize,
              total: totalCount,
            }}
          />
        </Card>
        <Modal
          title="请填写驳回原因"
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={() => this.swithModel(false)}
          onOk={() => this.handleAct(record.id, 3)}
          okText="确认"
          cancelText="取消"
        >
          <Input.TextArea onChange={(e: any) => this.setState({ reason: e.target.value })} />
        </Modal>
        <Modal
          title="请填写驳回原因"
          visible={this.state.visible2}
          destroyOnClose={true}
          onCancel={() => this.swithModel2(false)}
          onOk={this.handleActionOk}
          okText="确认"
          cancelText="取消"
        >
          <Input.TextArea onChange={(e: any) => this.setState({ reason: e.target.value })} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
